import 'dart:async';

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:ceramics/model/ab_config.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/login/ab_guide_page.dart';
import 'package:ceramics/pages/login/ab_login_page.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_init_db.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/util/ab_log.dart';
import 'package:ceramics/util/ab_log_util.dart';
import 'package:ceramics/util/ab_store_kit.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'bindings.dart';
import 'pages/main/ab_main_tab_page.dart';

bool firstLoad = true;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initDB();
  LogPvManger.stat(page: 'launch');
  ABStoreKit().startListen();
  await ABSingleton.initUser();
  timeRequestATT();
  if (ABSingleton.isLogin) {}
  var sp = await SharedPreferences.getInstance();
  var firstOpen = sp.getBool('firstOpen') ?? true;
  runApp(CustomApp(
      child: firstOpen
          ? const ABGuidePage()
          : ABSingleton.isLogin
          ? const ABMainTabPage()
          : const ABLoginPage()));
}

Future<bool> checkNetwork() async {
  final List<ConnectivityResult> connectivityResult = [await (Connectivity().checkConnectivity())];

// This condition is for demo purposes only to explain every connection type.
// Use conditions which work for your requirements.
  if (connectivityResult.contains(ConnectivityResult.mobile)) {
    // Mobile network available.
    return true;
  } else if (connectivityResult.contains(ConnectivityResult.wifi)) {
    return true;
    // Wi-fi is available.
    // Note for Android:
    // When both mobile and Wi-Fi are turned on system will return Wi-Fi only as active network type
  } else if (connectivityResult.contains(ConnectivityResult.ethernet)) {
    return true;
    // Ethernet connection available.
  } else if (connectivityResult.contains(ConnectivityResult.vpn)) {
    // Vpn connection active.
    // Note for iOS and macOS:
    // There is no separate network interface type for [vpn].
    // It returns [other] on any device (also simulator)
  } else if (connectivityResult.contains(ConnectivityResult.bluetooth)) {
    // Bluetooth connection available.
  } else if (connectivityResult.contains(ConnectivityResult.other)) {
    // Connected to a network which is not in the above mentioned networks.
  } else if (connectivityResult.contains(ConnectivityResult.none)) {
    // No available network types
  }
  // toast('no network connection');
  return false;
}

timeRequestATT() {
  Timer.periodic(const Duration(seconds: 2), (timer) {
    // 在这里执行你想要的任务
    requestATT();
  });
}

void requestATT() async {
  final TrackingStatus status =
      await AppTrackingTransparency.trackingAuthorizationStatus;
  if (status == TrackingStatus.notDetermined) {
    Future.delayed(const Duration(seconds: 2), () async {
      await AppTrackingTransparency.requestTrackingAuthorization();
    });
  } else {
// 释放定时器
  }
}

class CustomApp extends StatefulWidget {
  const CustomApp({Key? key, required this.child}) : super(key: key);
  final Widget child;

  @override
  State<CustomApp> createState() => _CustomAppState();
}

class _CustomAppState extends State<CustomApp> {

  late StreamSubscription<ConnectivityResult> _subscription;

  @override
  void initState() {
    super.initState();
    _subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.none) {
        if (!firstLoad) {
          toast('no network connection');
          firstLoad = false;
        }
      }
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      locale: const Locale('en', 'US'),
      supportedLocales: const [Locale('en', 'US')],
      theme: ThemeData(
          appBarTheme: const AppBarTheme(
            backgroundColor: Color(0x00FFFFFF),
            foregroundColor: ABStyles.darkBlack,
            elevation: 0,
            titleTextStyle: TextStyle(
              color: ABStyles.darkBlack,
              fontSize: 20,
              fontFamily: "RacingSansOne",
            ),
          ),
          outlinedButtonTheme: OutlinedButtonThemeData(
            style: OutlinedButton.styleFrom(
                foregroundColor: ABStyles.darkBlack,
                textStyle:
                    const TextStyle(fontSize: 16, color: ABStyles.darkBlack),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25),
                ),
                side: const BorderSide(color: ABStyles.darkBlack)),
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ElevatedButton.styleFrom(
              textStyle:
                  const TextStyle(fontSize: 16, color: ABStyles.darkBlack),
              minimumSize: const Size(0, 50),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25),
              ),
            ),
          ),
          dialogTheme: const DialogTheme(
              backgroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12)))),
          bottomNavigationBarTheme: const BottomNavigationBarThemeData(
            backgroundColor: Colors.red,
            elevation: 0,
            selectedItemColor: ABStyles.orange,
            unselectedItemColor: ABStyles.darkBlack,
            selectedLabelStyle:
                TextStyle(fontFamily: "RacingSansOne", color: ABStyles.orange),
            unselectedLabelStyle: TextStyle(
                fontFamily: "RacingSansOne", color: ABStyles.darkBlack),
          )),
      home: widget.child,
      builder: EasyLoading.init(),
      debugShowCheckedModeBanner: false,
      initialBinding: putController(),
    );
  }
}
